<?php

namespace app\agent\model;

use app\common\library\helper;
use app\common\model\BaseModel as amodel;
use think\Db;
use think\Session;

/**
 * 代理模型
 */
class Shop extends amodel{
    /**
     * 后台首页数据
     */
    public function getAgentData($agentInfo){
        if($agentInfo['type']==0){
            //品牌商
            $data['hehuoren'] = $this->getHuorenCount($agentInfo);
            $data['yuangong'] = $this->getYuanGongCount($agentInfo);
            $data['xiaji'] = $this->getNextCount($agentInfo);
            $data['water'] = $this->getShangWater($agentInfo);
            $data['yunyingshangCount']= $this->getYunyingCount($agentInfo);
            $data['shanghucount']=$this->getShnghuCount($agentInfo);
            $data['fenhon']=$this->getFenhonWater($agentInfo);

        }elseif ($agentInfo['type']==1){
            //运营商
            if($agentInfo['level']==1){
                //个人性质的运营商  统计合伙人信息，商户信息
                $data['xiaji'] = $this->getNextCount($agentInfo);
                $data['hehuoren'] = $this->getHuorenCount($agentInfo);
                $data['water'] = $this->getShangWater($agentInfo);
                $data['shanghucount']=$this->getShnghuCount($agentInfo);
                $data['yuangong'] = $this->getYuanGongCount($agentInfo);
                $data['fenhon']=$this->getFenhonWater($agentInfo);
            }else{
                //企业性质的运营商，统计合伙人信息，代言人信息，商户信息
                $data['xiaji'] = $this->getNextCount($agentInfo);
                $data['hehuoren'] = $this->getHuorenCount($agentInfo);
                $data['yuangong'] = $this->getYuanGongCount($agentInfo);
                $data['water'] = $this->getShangWater($agentInfo);
                $data['shanghucount']=$this->getShnghuCount($agentInfo);
                $data['fenhon']=$this->getFenhonWater($agentInfo);
            }
        }elseif ($agentInfo['type']==2){
            //合伙人
            if($agentInfo['level']==1){
                //个人性质的合伙人，只统计商户数据
                $data['xiaji'] = $this->getNextCount($agentInfo);
                $data['water'] = $this->getShangWater($agentInfo);
                $data['shanghucount']=$this->getShnghuCount($agentInfo);
                $data['fenhon']=$this->getFenhonWater($agentInfo);
            }else{
                //企业性质的合伙人，统计代言人数据和商户数据
                $data['xiaji'] = $this->getNextCount($agentInfo);
                /* $data['yuangong'] = $this->getYuanGongCount($agentInfo);*/
                $data['water'] = $this->getShangWater($agentInfo);
                $data['shanghucount']=$this->getShnghuCount($agentInfo);
                $data['fenhon']=$this->getFenhonWater($agentInfo);
            }
        }else{
            //代言人，只统计商户数据
            $data['xiaji'] = $this->getNextCount($agentInfo);
            $data['water'] = $this->getShangWater($agentInfo);
            $data['shanghucount']=$this->getShnghuCount($agentInfo);
        }
        return $data;
    }
    /*
     * api数据统计
     */
    public function getwater($agentInfo){

        \think\Log::info('api数据统计：'.json_encode($agentInfo));
        $countInfo=$this->getNextCountapi($agentInfo);
        $countInfos=$this->getShangWaterapi($agentInfo);
        $divideStoreAmount['xiaji']['dailiCount']=$countInfo['dailiCount'];
        $divideStoreAmount['xiaji']['shanghuCount']=$countInfo['shanghuCount'];
        $divideStoreAmount['water']['today']['amount']=$countInfos['today']['amount'];
        $divideStoreAmount['water']['today']['money']=$countInfos['today']['money'];
        $divideStoreAmount['water']['yesterday']['amount']=$countInfos['yesterday']['amount'];
        $divideStoreAmount['water']['yesterday']['money']=$countInfos['yesterday']['money'];
        $divideStoreAmount['water']['month']['amount']=$countInfos['month']['amount'];
        $divideStoreAmount['water']['month']['money']=$countInfos['month']['money'];
        $divideStoreAmount['water']['lastMonth']['amount']=$countInfos['lastMonth']['amount'];
        $divideStoreAmount['water']['lastMonth']['money']=$countInfos['lastMonth']['money'];
        return $divideStoreAmount;
    }
    /*
     * 获取代理分红流水记录
     */
    private function getFenhonWater($data){
        if($data['type']==0){
            $info=Db::name('agent')->where(['type'=>['in','0,1,2,3'],'pinpai_id'=>$data['pinpai_id']])->select();
            //下级信息，获取下级总数量
            $resNext=$this->get_all_childs($info->toArray(),$data['agent_id']);
            $resNext[]=$data['agent_id'];
        }else{
            $info=Db::name('agent')->where(['recommend_id'=>$data['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach($info as $k=>$v){
                    $resNext[]=$v['agent_id'];
                }
            }
            $resNext[]=$data['agent_id'];
        }
        $wxappInfo=Db::name('wxapp')->where(['agent_id'=>['in',$resNext]])->field('wxapp_id')->select();
        $str='';
        if($wxappInfo){
            foreach($wxappInfo as $k=>$v){
                if(empty($str)){
                    $str=(string)$v['wxapp_id'];
                }else{
                    $str.=','.$v['wxapp_id'];
                }
            }
        }else{
            return [
                'today'=>0,
                'month'=>0,
                'lastmonth'=>0,
                'yesterday'=>0,
                'dongjie'=>0,
                'lishi'=>0,
                'ketixian'=>0,
            ];
        }
        $lishi=Db::name('divide_service')->where('wxapp_id','in',$str)->where(['status'=>1,'agent_id'=>$data['agent_id']])->sum('amount');
        $today=Db::name('divide_service')->where('wxapp_id','in',$str)->where(['status'=>1,'agent_id'=>$data['agent_id']])->whereTime('create_time', 'today')->sum('amount');
        $month=Db::name('divide_service')->where('wxapp_id','in',$str)->where(['status'=>1,'agent_id'=>$data['agent_id']])->whereTime('create_time', 'month')->sum('amount');
        $yesterday=Db::name('divide_service')->where('wxapp_id','in',$str)->where(['status'=>1,'agent_id'=>$data['agent_id']])->whereTime('create_time', 'yesterday')->sum('amount');
        $lastmonth=Db::name('divide_service')->where('wxapp_id','in',$str)->where(['status'=>1,'agent_id'=>$data['agent_id']])->whereTime('create_time', 'last month')->sum('amount');
        $dongjie=$money=Db::name('agent_cashout')->where(['agent_id'=>$data['agent_id'],'sh_status'=>['<>',2]])->sum('money');
        $ketixian=$lishi-$dongjie;
        return [
            'today'=>sprintf("%.2f",($today)),
            'month'=>sprintf("%.2f",($month)),
            'lastmonth'=>sprintf("%.2f",($lastmonth)),
            'yesterday'=>sprintf("%.2f",($yesterday)),
            'dongjie'=>sprintf("%.2f",($dongjie)),
            'lishi'=>sprintf("%.2f",($lishi)),
            'ketixian'=>sprintf("%.2f",($ketixian)),
        ];

    }
    private function getShnghuCount($data){
        if($data['type']==0){
            $info=Db::name('agent')->where(['type'=>['in','0,1,2,3'],'pinpai_id'=>$data['pinpai_id']])->select();
            //下级信息，获取下级总数量
            $resNext=$this->get_all_childs($info->toArray(),$data['agent_id']);
            $resNext[]=$data['agent_id'];
        }else{
            $info=Db::name('agent')->where(['recommend_id'=>$data['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach($info as $k=>$v){
                    $resNext[]=$v['agent_id'];
                }
            }
            $resNext[]=$data['agent_id'];
        }
        //今日
        $today=Db::name('wxapp')
            ->where(['agent_id'=>['in',$resNext]])
            ->where(['is_delete'=>0])
            ->whereTime('create_time', 'today')
            ->field('wxapp_id')
            ->count();
        //昨日
        $yesterday=Db::name('wxapp')
            ->where(['agent_id'=>['in',$resNext]])
            ->where(['is_delete'=>0])
            ->whereTime('create_time', 'yesterday')
            ->field('wxapp_id')
            ->count();
        //本月
        $month=Db::name('wxapp')
            ->where(['agent_id'=>['in',$resNext]])
            ->where(['is_delete'=>0])
            ->whereTime('create_time', 'month')
            ->field('wxapp_id')
            ->count();
        //上月
        $lastmonth=Db::name('wxapp')
            ->where(['agent_id'=>['in',$resNext]])
            ->where(['is_delete'=>0])
            ->whereTime('create_time', 'last month')
            ->field('wxapp_id')
            ->count();
        //总数量
        $total=Db::name('wxapp')
            ->where(['agent_id'=>['in',$resNext]])
          
            ->field('wxapp_id')
            ->count();
        if(empty($wxappArray)){
            $shanghu['today']['amount']=$today;
            $shanghu['yesterday']['amount']=$yesterday;
            $shanghu['month']['amount']=$month;
            $shanghu['lastMonth']['amount']=$lastmonth;
            $shanghu['total']['amount']=$total;
            return $shanghu;
        }
    }
    /*
     * api 获取商户流水，按时间查询 今日  昨日  今月  上月
     */
    private function getShangWaterapi($data){
        if($data['type']==0){
            $info=Db::name('agent')->where(['type'=>['in','0,1,2,3'],'pinpai_id'=>$data['pinpai_id']])->select();
            //下级信息，获取下级总数量
            $resNext=$this->get_all_childs($info->toArray(),$data['agent_id']);
            $resNext[]=$data['agent_id'];
        }else{
            $info=Db::name('agent')->where(['recommend_id'=>$data['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach ($info as $k=>$v){
                    $resNext[]=$v['agent_id'];
                }
            }
            $resNext[]=$data['agent_id'];
        }
        //获取所有下级代理添加的商户信息
        $wxappInfo=Db::name('wxapp')->where(['agent_id'=>['in',$resNext],'active'=>1])->field('wxapp_id')->select();
        $wxappInfo=$wxappInfo->toArray();
        $wxappArray=[];
        if($wxappInfo){
            foreach($wxappInfo as $k=>$v){
                $wxappArray[]=$v['wxapp_id'];
            }
        }
        if(empty($wxappArray)){
            $divideStoreAmount['today']['amount']=0;
            $divideStoreAmount['today']['money']=0;
            $divideStoreAmount['yesterday']['amount']=0;
            $divideStoreAmount['yesterday']['money']=0;
            $divideStoreAmount['month']['amount']=0;
            $divideStoreAmount['month']['money']=0;
            $divideStoreAmount['lastMonth']['amount']=0;
            $divideStoreAmount['lastMonth']['money']=0;
            return $divideStoreAmount;
        }
        //今日
        /* $today=Db::name('0rder')->whereTime('create_time', 'today')->where(['agent_id'=>['in',$resNext],'status'=>1])->count();
         $todayMoney=Db::name('divide_store')->whereTime('create_time', 'today')->where(['agent_id'=>['in',$resNext],'status'=>1])->sum('amount');
         //昨日
         $yesterday=Db::name('divide_store')->whereTime('create_time', 'yesterday')->where(['agent_id'=>['in',$resNext],'status'=>1])->count();
         $yesterdayMoney=Db::name('divide_store')->whereTime('create_time', 'yesterday')->where(['agent_id'=>['in',$resNext],'status'=>1])->sum('amount');
         //今月
         $month=Db::name('divide_store')->whereTime('create_time', 'month')->where(['agent_id'=>['in',$resNext],'status'=>1])->count();
         $monthMoney=Db::name('divide_store')->whereTime('create_time', 'month')->where(['agent_id'=>['in',$resNext],'status'=>1])->sum('amount');
         //上月
         $lastMonth=Db::name('divide_store')->whereTime('create_time', 'last month')->where(['agent_id'=>['in',$resNext],'status'=>1])->count();
         $lastMonthMoney=Db::name('divide_store')->whereTime('create_time', 'last month')->where(['agent_id'=>['in',$resNext],'status'=>1])->sum('amount');*/
        $today=Db::name('order')
            ->whereTime('create_time', 'today')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $todayMoney=Db::name('order')
            ->whereTime('create_time', 'today')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        //昨日
        $yesterday=Db::name('order')
            ->whereTime('create_time', 'yesterday')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $yesterdayMoney=Db::name('order')
            ->whereTime('create_time', 'yesterday')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        //今月
        $month=Db::name('order')
            ->whereTime('create_time', 'month')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $monthMoney=Db::name('order')
            ->whereTime('create_time', 'month')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        //上月
        $lastMonth=Db::name('order')
            ->whereTime('create_time', 'last month')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $lastMonthMoney=Db::name('order')
            ->whereTime('create_time', 'last month')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        $divideStoreAmount['today']['amount']=$today;
        $divideStoreAmount['today']['money']=$todayMoney;
        $divideStoreAmount['yesterday']['amount']=$yesterday;
        $divideStoreAmount['yesterday']['money']=$yesterdayMoney;
        $divideStoreAmount['month']['amount']=$month;
        $divideStoreAmount['month']['money']=$monthMoney;
        $divideStoreAmount['lastMonth']['amount']=$lastMonth;
        $divideStoreAmount['lastMonth']['money']=$lastMonthMoney;
        return $divideStoreAmount;
    }

    /*
     * api获取当前登录代理的所有下级代理，以及商户数量
     */
    private function getNextCountapi($data){
        if($data['type']==0){
            //下级信息，获取下级总数量
            $info=Db::name('agent')->where(['pinpai_id'=>$data['pinpai_id']])->select();
            if($info->toArray()){
                //获取当前代理所有下级添加的商户数量
                $a=$this->get_all_childs($info->toArray(),$data['agent_id']);
                if($a){
                    $resNext=$this->get_all_child($info->toArray(),$data['agent_id'],'3');
                    $counts=count($resNext);
                    $count=count($a)-$counts;
                    $a[]=$data['agent_id'];
                }else{
                    $count=0;
                    $a[]=$data['agent_id'];
                }
                $storeCount=Db::name('wxapp')->where(['agent_id'=>['in',$a]])->field('wxapp_id')->count();
                $countInfo['dailiCount']=$count;
                $countInfo['shanghuCount']=$storeCount;
            }else{
                $countInfo['dailiCount']=0;
                $countInfo['shanghuCount']=0;
            }
        }else{
            //获取直属下级
            $info=Db::name('agent')->where(['recommend_id'=>$data['agent_id'],'type'=>['<>',3]])->select();
            if($info){
                $a=[];
                foreach($info as $k=>$v){
                    $a[]=$v['agent_id'];
                }
                $a[]=$data['agent_id'];
                $count=count($info);
                $storeCount=Db::name('wxapp')->where(['agent_id'=>['in',$a]])->field('wxapp_id')->count();
                $countInfo['dailiCount']=$count;
                $countInfo['shanghuCount']=$storeCount;
            }else{
                $countInfo['dailiCount']=0;
                $countInfo['shanghuCount']=0;
            }
        }
        return $countInfo;
    }
    //递归获取所有的子分类的ID(带类型)
    private function get_all_child($array,$id,$type){
        $arr = array();
        foreach($array as $v){
            if($v['recommend_id'] == $id ){
                if($v['type']==$type){
                    $arr[] = $v['agent_id'];
                }
                $arr = array_merge($arr,$this->get_all_child($array,$v['agent_id'],$type));
            };
        };
        return $arr;
    }

    /*
     * 运营商总数
     */
    private function getYunyingCount($data){
        //获取当前品牌商的所有运营商总数
        $count=Db::name('agent')->where(['pinpai_id'=>$data['pinpai_id'],'type'=>1])->count();
        return $count;
    }
    /*
     * 合伙人总数
     */
    private function getHuorenCount($data){
        $agentInfo=Session::get('yoshop_agent.agent');
        if($data['type']==0){
            //品牌商
            $info=Db::name('agent')->where(['pinpai_id'=>$data['pinpai_id']])->select();
            if($info){
                //下级信息，获取下级总数量
                $resNext=$this->get_all_child($info->toArray(),$agentInfo['agent_id'],'2');
                //var_dump($resNext);
                return count($resNext);
            }
        }else{
            $info=Db::name('agent')->where(['recommend_id'=>$agentInfo['agent_id'],'type'=>2])->select();
            if($info){
                return count($info);
            }
        }
        return 0;
    }
    /*
     * 获取代言人总数
     */
    private function getYuanGongCount($data){
        $agentInfo=Session::get('yoshop_agent.agent');
        if($data['type']==0) {
            $info = Db::name('agent')->where(['pinpai_id' => $data['pinpai_id']])->select();
            if ($info) {
                //下级信息，获取下级总数量
                $agentInfo = Session::get('yoshop_agent.agent');
                $resNext = $this->get_all_child($info->toArray(), $agentInfo['agent_id'], '3');
                return count($resNext);
            }
        }else{
            $info=Db::name('agent')->where(['recommend_id'=>$agentInfo['agent_id'],'type'=>3])->select();
            if($info){
                return count($info);
            }
        }
        return 0;
    }
    /*
     * 获取当前登录代理的所有下级代理，以及商户数量
     */
    private function getNextCount($data){
        $agentInfo=Session::get('yoshop_agent.agent');
        if($data['type']==0){
            $info=Db::name('agent')->where(['pinpai_id'=>$data['pinpai_id']])->select();
            //下级信息，获取下级总数量
            if($info->toArray()){
                //获取当前代理所有下级添加的商户数量
                $a=$this->get_all_childs($info->toArray(),$agentInfo['agent_id']);
                if($a){
                    //去掉代言人数量
                    $resNext=$this->get_all_child($info->toArray(),$agentInfo['agent_id'],'3');
                    $counts=count($resNext);
                    $count=count($a)-$counts;
                    $a[]=$agentInfo['agent_id'];
                }else{
                    $count=0;
                    $a[]=$agentInfo['agent_id'];
                }
                $storeCount=Db::name('wxapp')->where(['agent_id'=>['in',$a]])->field('wxapp_id')->count();
                $countInfo['dailiCount']=$count;
                $countInfo['shanghuCount']=$storeCount;
                return $countInfo;
            }else{
                $countInfo['dailiCount']=0;
                $storeCount=Db::name('wxapp')->where(['agent_id'=>$agentInfo['agent_id']])->field('wxapp_id')->count();
                $countInfo['shanghuCount']=$storeCount;
                return $countInfo;
            }
        }else{
            $xiaji=Db::name('agent')->where(['recommend_id'=>$agentInfo['agent_id'],'type'=>['in','0,1,2']])->select();
            $arr=[];
            if($xiaji){
                foreach($xiaji as $k=>$v){
                    $arr[]=$v['agent_id'];
                }
                $arr[]=$agentInfo['agent_id'];
                $xijicount=count($xiaji);
                $storeCount=Db::name('wxapp')->where(['agent_id'=>['in',$arr]])->field('wxapp_id')->count();
                $countInfo['dailiCount']=$xijicount;
                $countInfo['shanghuCount']=$storeCount;
            }else{
                $countInfo['dailiCount']=0;
                $storeCount=Db::name('wxapp')->where(['agent_id'=>$agentInfo['agent_id']])->field('wxapp_id')->count();
                $countInfo['shanghuCount']=$storeCount;
            }
            return $countInfo;
        }

    }

    //获取所有下级id  (不包含类型)
    private function get_all_childs($array,$id){
        $arr = array();
        foreach($array as $v){
            if($v['recommend_id'] == $id ){
                $arr[] = $v['agent_id'];
                $arr = array_merge($arr,$this->get_all_childs($array,$v['agent_id']));
            };
        };
        return $arr;
    }
    /*
     * 获取商户流水，按时间查询 今日  昨日  今月  上月
     */
    private function getShangWater($data){
        if($data['type']==0){
            $info=Db::name('agent')->where(['type'=>['in','0,1,2,3'],'pinpai_id'=>$data['pinpai_id']])->select();
            //下级信息，获取下级总数量
            $resNext=$this->get_all_childs($info->toArray(),$data['agent_id']);
            $resNext[]=$data['agent_id'];
        }else{
            $info=Db::name('agent')->where(['recommend_id'=>$data['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach($info as $k=>$v){
                    $resNext[]=$v['agent_id'];
                }
            }
            $resNext[]=$data['agent_id'];
        }

        //获取所有下级代理添加的商户信息
        $wxappInfo=Db::name('wxapp')->where(['agent_id'=>['in',$resNext],'active'=>1])->field('wxapp_id')->select();
        $wxappInfo=$wxappInfo->toArray();
        $wxappArray=[];
        if($wxappInfo){
            foreach($wxappInfo as $k=>$v){
                $wxappArray[]=$v['wxapp_id'];
            }
        }
        if(empty($wxappArray)){
            $divideStoreAmount['today']['amount']=0;
            $divideStoreAmount['today']['money']=0;
            $divideStoreAmount['yesterday']['amount']=0;
            $divideStoreAmount['yesterday']['money']=0;
            $divideStoreAmount['month']['amount']=0;
            $divideStoreAmount['month']['money']=0;
            $divideStoreAmount['lastMonth']['amount']=0;
            $divideStoreAmount['lastMonth']['money']=0;
            return $divideStoreAmount;
        }

        //今日
        $today=Db::name('order')
            ->whereTime('create_time', 'today')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $todayMoney=Db::name('order')
            ->whereTime('create_time', 'today')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');

        //昨日
        $yesterday=Db::name('order')
            ->whereTime('create_time', 'yesterday')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $yesterdayMoney=Db::name('order')
            ->whereTime('create_time', 'yesterday')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        //今月
        $month=Db::name('order')
            ->whereTime('create_time', 'month')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $monthMoney=Db::name('order')
            ->whereTime('create_time', 'month')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        //上月
        $lastMonth=Db::name('order')
            ->whereTime('create_time', 'last month')
            ->where(['wxapp_id'=>['in',$wxappArray],'pay_status'=>20])
            ->count();
        $lastMonthMoney=Db::name('order')
            ->whereTime('create_time', 'last month')
            ->where(['wxapp_id'=>['in',$wxappArray],'is_delete'=>0,'pay_status'=>20])
            ->sum('pay_price');
        $divideStoreAmount['today']['amount']=$today;
        $divideStoreAmount['today']['money']=$todayMoney;
        $divideStoreAmount['yesterday']['amount']=$yesterday;
        $divideStoreAmount['yesterday']['money']=$yesterdayMoney;
        $divideStoreAmount['month']['amount']=$month;
        $divideStoreAmount['month']['money']=$monthMoney;
        $divideStoreAmount['lastMonth']['amount']=$lastMonth;
        $divideStoreAmount['lastMonth']['money']=$lastMonthMoney;
        return $divideStoreAmount;
    }
    /*
    * 增加门店信息
    */
    public function add($data){
        return Db::name('store_shop')->insert($data);
    }
}